#include "mainwindow.h"


extern QSqlDatabase db;
extern QString get_setting(QString);
extern void set_setting(QString,QString);
extern QString base_path;

#ifdef Q_WS_MAEMO_5

#include <QtMaemo5>
#include <QtGui/QX11Info>
#include <X11/Xlib.h>
#include <X11/Xatom.h>

void MainWindow::grabZoomKeys(bool grab)
     {
         if (!winId()) {
             qWarning("Can't grab keys unless we have a window id");
             return;
         }


         unsigned long val = (grab) ? 1 : 0;
         Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
         if (!atom) {
             return;
         }


         XChangeProperty (QX11Info::display(),
                 winId(),
                 atom,
                 XA_INTEGER,
                 32,
                 PropModeReplace,
                 reinterpret_cast<unsigned char *>(&val),
                 1);
     }

void MainWindow::headphoneEvent(QString what,QString how)
{
    if (what != "ButtonPressed" || how != "connection")
        return;
    bool present = QDBusInterface ("org.freedesktop.Hal",
                    "/org/freedesktop/Hal/devices/platform_headphone",
                    "org.freedesktop.Hal.Device",
                    QDBusConnection::systemBus()).call ("GetProperty", "button.state.value").arguments().at(0).toBool();
// head disconnect
    if (!present)
    {
        switch(on_head_dis){
        case 1:
            moo->pause();
            break;
        case 2:
            device->setMuted(true);
            break;
        case 3:
            qApp->exit();
            break;
        }

    }

// head connect

    if (present)
    {
        switch(on_head_con){
        case 1:
            moo->play();
            break;
        case 2:
            device->setMuted(false);
            break;
        }

    }

}

void MainWindow::dbus(QString what,QString how){
    qDebug(what.toAscii());
    qDebug(how.toAscii());
}

#endif

void MainWindow::m3uForDir(){
    QString path=QFileDialog::getExistingDirectory(this,tr("Select directory"),"/home/user/MyDocs");
    if (path.isEmpty())return;

    QString spath=QFileDialog::getSaveFileName(this,tr("Save m3u as"),"/home/user/MyDocs","m3u(*.m3u)",new QString("m3u(*.m3u)"));
    if (spath.isEmpty())return;

    QFile fl(spath);
    if (!fl.open(QFile::Text|QFile::WriteOnly)){
        QMessageBox dt;
        dt.setText(tr("Access error while trying to open file %1").arg(spath));
        dt.exec();
        return;
    }

    QTextStream out(&fl);
     out << "#EXTM3U\n";

    QDir dr(path);
    dr.setNameFilters(namefilter);
    QDirIterator it(dr, QDirIterator::Subdirectories);
    int yt=0;
    while (it.hasNext()) {
        it.next();
        out<<QString("#EXTINF:0, %1\n").arg(it.fileName());
        out<<it.filePath()<<"\n";
        yt++;
    }
    fl.close();

    QMessageBox dt2;
    dt2.setText(tr("Playlist created,files count:%1").arg(yt));
    dt2.exec();
}

void MainWindow::inet(QListWidgetItem* item){
    set_setting("source_list","1");
inet_source=1;


    moo->setCurrentSource(ilist.value(ui.listWidget_2->currentRow()).at(0));
    moo->play();



}

void MainWindow::load_inet(){
QString lst=get_setting("list_path");
if (lst.isEmpty())lst=base_path+"tplayer-inet.m3u";


QFile file(lst);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
    QMessageBox td;
    td.setText(tr("Error while loading %1 playlist").arg(lst));
    td.exec();
    return;}

ui.listWidget_2->clear();
ilist.clear();

QTextStream in(&file);


     QString line = in.readLine();

      if (line!="#EXTM3U")return; // here i should create .pls\.cue file support

int t=0;
        while (!in.atEnd()) {

           line = in.readLine();


           QRegExp rx("^#EXTINF:\\d*,(.*)$") ;
           rx.indexIn(line);
           QString title=rx.cap(1);
           line = in.readLine();
           ilist.insert(t++,QStringList()<<line<<title<<tr("Internet radio"));

              ui.listWidget_2->addItem(title);
        }


        ui.pushButton_16->setEnabled(true);
}

MainWindow::MainWindow(QWidget *parent)    : QMainWindow(parent)
{




metaInformationResolver = new Phonon::MediaObject(this);

    ui.setupUi(this);



moo = new Phonon::MediaObject;;
device = new Phonon::AudioOutput;
audioPath=Phonon::createPath(moo, device);




//eq
QList<Phonon::EffectDescription> effectDescriptions =
             Phonon::BackendCapabilities::availableAudioEffects();
foreach (Phonon::EffectDescription effectDescription, effectDescriptions)
    {

        if ((effectDescription.name() == "KEqualizer") || (effectDescription.name() == "equalizer-10bands"))
        {

            ui.pushButton_5->setEnabled(true);
            eqEffect = new Phonon::Effect(effectDescription);

        }
    }

QVBoxLayout* vb = new QVBoxLayout(ui.frame_7);
QHBoxLayout* lt = new QHBoxLayout;
int min=-12,max=12;
for (int i = 0; i < 10; ++i)
{
    QSlider* s = new QSlider (Qt::Vertical);
    s->setMinimum(min);
    s->setMaximum(max);
    s->setMinimumHeight(180);
    s->setValue(0);
    connect (s, SIGNAL(valueChanged(int)), this, SLOT(sliderChanged(int)));
    QVBoxLayout* tmpLay = new QVBoxLayout;
    tmpLay->addWidget(s);
    lt->addLayout(tmpLay);
    sliders.append(s);
}
QCheckBox *enabled = new QCheckBox(tr("Enable equalizer"));
if (get_setting("eq_state")=="1")enabled->setChecked(true); else enabled->setChecked(false);
toggleEqualizer(enabled->isChecked());
connect(enabled, SIGNAL(toggled(bool)), this, SLOT(toggleEqualizer(bool)));


vb->addWidget(enabled);
vb->addLayout(lt);
QPushButton *reset = new QPushButton(tr("Functions"));

eq_menu=new QMenu;
load_eqs();

connect (reset, SIGNAL(clicked()), this,SLOT(eq_fn_click()));
vb->addWidget(reset);
setLayout(vb);


//
slider = new Phonon::SeekSlider(ui.widget_2);
volume=new Phonon::VolumeSlider(ui.widget_2);
ui.verticalLayout_3->addWidget(slider);
ui.verticalLayout_3->addWidget(volume);
slider->setMediaObject(moo);
volume->setAudioOutput(device);

volume->setOrientation(Qt::Horizontal);


opt=new options();
rotate=0;
load();



//new style
ui.frame_10->hide();
connect (ui.pushButton_17,SIGNAL(clicked()),this,SLOT(about()));
connect (ui.pushButton_14,SIGNAL(clicked()),this,SLOT(click6()));
connect (ui.pushButton_15,SIGNAL(clicked()),this,SLOT(click7()));
connect (ui.pushButton_16,SIGNAL(clicked()),this,SLOT(click8()));

connect (ui.pushButton_19,SIGNAL(clicked()),this,SLOT(dart()));
connect (ui.pushButton_20,SIGNAL(clicked()),this,SLOT(dart2()));
connect (ui.pushButton_21,SIGNAL(clicked()),opt,SLOT(exec()));
connect (ui.checkBox_2,SIGNAL(stateChanged(int)),this,SLOT(fmtx_change(int)));

connect(ui.listWidget_2,SIGNAL(itemDoubleClicked(QListWidgetItem*)),this,SLOT(inet(QListWidgetItem*)));

connect(ui.pushButton_23,SIGNAL(clicked()),this,SLOT(i_fn_click()));
connect (ui.pushButton_22,SIGNAL(clicked()),this,SLOT(inform()));
connect (ui.pushButton_24,SIGNAL(clicked()),this,SLOT(m3uForDir()));
//

load_inet();



connect(ui.pushButton_10,SIGNAL(clicked()),this,SLOT(pl_sf_click()));


connect (opt,SIGNAL(accepted()),this,SLOT(load()));
          connect(metaInformationResolver, SIGNAL(stateChanged(Phonon::State,Phonon::State)), this, SLOT(metaStateChanged(Phonon::State,Phonon::State)));
          connect(ui.pushButton,SIGNAL(clicked()),this,SLOT(click1()));
          connect(ui.pushButton_2,SIGNAL(clicked()),this,SLOT(click2()));
          connect(ui.pushButton_3,SIGNAL(clicked()),this,SLOT(click3()));
          connect(ui.pushButton_4,SIGNAL(clicked()),this,SLOT(click4()));
          connect(ui.pushButton_5,SIGNAL(clicked()),this,SLOT(click5()));
          connect(ui.pushButton_11,SIGNAL(clicked()),this,SLOT(pl_fn_click()));
          connect(ui.pushButton_7,SIGNAL(clicked()),moo,SLOT(pause()));
          connect(ui.pushButton_7,SIGNAL(clicked()),moo,SLOT(stop()));
          connect(ui.pushButton_6,SIGNAL(clicked()),this,SLOT(play_pause()));
          connect (ui.pushButton_8,SIGNAL(clicked()),this,SLOT(prev()));
          connect (ui.pushButton_9,SIGNAL(clicked()),this,SLOT(next()));
          connect(moo,SIGNAL(stateChanged(Phonon::State,Phonon::State)),this,SLOT(changePlay(Phonon::State,Phonon::State)));
          connect(ui.listWidget,SIGNAL(itemDoubleClicked(QListWidgetItem*)),this,SLOT(currentItemChanged(QListWidgetItem*)));
          connect(moo,SIGNAL(finished()),this,SLOT(next()));
connect(qApp,SIGNAL(focusChanged(QWidget*,QWidget*)),this,SLOT(repaint()));
connect(device,SIGNAL(volumeChanged(qreal)),this,SLOT(volumeChanged(qreal)));
click1();



inet_source=get_setting("source_list").toLong();

reload();
int row=-1;
QString rw=get_setting("last_played");
if (!rw.trimmed().isEmpty()){
    QMapIterator<int,QStringList> idk(list);
    while(idk.hasNext()&&row==-1){
        idk.next();
        if (idk.value().at(0)==rw)row=idk.key();
        }
}

ui.listWidget->setCurrentRow(row);





int row2=-1;
rw=get_setting("last_played_l");
if (!rw.trimmed().isEmpty()){
    QMapIterator<int,QStringList> idk2(ilist);
    while(idk2.hasNext()&&row2==-1){
        idk2.next();
        if (idk2.value().at(0)==rw)row2=idk2.key();
        }
}
ui.listWidget_2->setCurrentRow(row2);


if (inet_source==0){
if (row!=-1)
 moo->setCurrentSource(list.value(ui.listWidget->currentRow()).at(0));
}else{
if (row2!=-1)
 moo->setCurrentSource(ilist.value(ui.listWidget_2->currentRow()).at(0));
}


#ifdef Q_WS_MAEMO_5
grabZoomKeys(true);
QAbstractKineticScroller *scroller =ui.textEdit->property("kineticScroller").value<QAbstractKineticScroller *>();
scroller->setEnabled(true);
QAbstractKineticScroller *scroller2 =ui.textEdit_2->property("kineticScroller").value<QAbstractKineticScroller *>();
scroller2->setEnabled(true);


    QDBusConnection::systemBus().connect(QString(), "/org/freedesktop/Hal/devices/platform_headphone", "org.freedesktop.Hal.Device", "Condition", this, SLOT(headphoneEvent(QString,QString)));


#endif

 QList<QWidget *> widgets = this->ui.centralwidget->findChildren<QWidget *>();
for (int i=0;i<widgets.count();i++)
     widgets.at(i)->installEventFilter(this);


if (row!=-1){
    if (on_start==1) play_pause();
    if (on_start==2 && QDBusInterface ("org.freedesktop.Hal",
                    "/org/freedesktop/Hal/devices/platform_headphone",
                    "org.freedesktop.Hal.Device",
                    QDBusConnection::systemBus()).call ("GetProperty", "button.state.value").arguments().at(0).toBool())play_pause();
}

eq_name=get_setting("last_eq");
if (eq_name.isEmpty())eq_name="Default";
load_eq(eq_name);



}

void MainWindow::load_eqs(){
    eq_menu->clear();
    QMenu *fn=new QMenu(tr("Equalizer"),eq_menu);
     fn->addAction(tr("Save to new"),this,SLOT(save_eq_d()));
     fn->addAction(tr("Save current"),this,SLOT(save_eq()));
     fn->addAction(tr("Remove current"),this,SLOT(rem_eq()));
eq_menu->addMenu(fn);

    QString sql="SELECT `name` FROM `equalizer` WHERE 1";
    QSqlQuery query(sql);
         while (query.next()) {
             QString nm=query.value(0).toString();
             eq_menu->addAction(nm,this,SLOT(eq_load_mn()));
         }



}

void MainWindow::eq_fn_click(){
    eq_menu->exec(QCursor::pos());
}

void MainWindow::eq_load_mn(){
QAction *action = qobject_cast<QAction *>(sender());
load_eq(action->text());
}

void MainWindow::load_eq(QString name){
    QString sql="SELECT * FROM `equalizer` WHERE `name`='"+name+"'";
    QSqlQuery query(sql);
         while (query.next()) {
             for (int i=0;i<10;i++){
             QString nm=query.value(i+1).toString();
            sliders[i]->setValue(nm.toLong());
                }
         }

         eq_name=name;
     set_setting("last_eq",name);
}
void MainWindow::save_eq_d(){
    QDialog *d=new QDialog();
    QVBoxLayout *h=new QVBoxLayout(d);
    QLabel *y=new QLabel(tr("<center>New equalizer name</center>"),d);
    QLineEdit *u=new QLineEdit(d);
    QPushButton *ok=new QPushButton(tr("Create equalizer"),d);
    h->addWidget(y);
    h->addWidget(u);
    h->addWidget(ok);
    connect (ok,SIGNAL(clicked()),d,SLOT(accept()));
    d->exec();
    QString nn=u->text().replace("'","''").trimmed();

if (!nn.isEmpty())save_eq(nn);
}

void MainWindow::save_eq(){
    save_eq(eq_name);
}
void MainWindow::rem_eq(){
db.exec("DELETE FROM `equalizer` WHERE `name`='"+eq_name+"'");
}
void MainWindow::save_eq(QString name){
db.exec("DELETE FROM `equalizer` WHERE `name`='"+name+"'");
QString sql=QString("INSERT INTO `equalizer` (name,eq1,eq2,eq3,eq4,eq5,eq6,eq7,eq8,eq9,eq10) "
        "VALUES ('%1','%2','%3','%4','%5','%6','%7','%8','%9','%10','%11')")
            .arg(name)
            .arg(sliders[0]->value())
            .arg(sliders[1]->value())
            .arg(sliders[2]->value())
            .arg(sliders[3]->value())
            .arg(sliders[4]->value())
            .arg(sliders[5]->value())
            .arg(sliders[6]->value())
            .arg(sliders[7]->value())
            .arg(sliders[8]->value())
            .arg(sliders[9]->value());


    if(!db.exec(sql).isValid())
   qDebug(db.lastError().text().toAscii());
db.commit();



load_eqs();
}

void MainWindow::reload(){
    currentQuery=get_setting("query");
    if (currentQuery.trimmed().isEmpty())
           currentQuery="SELECT * FROM tracks WHERE 1";



QFile file2(base_path+".tplayer-lists");
   if (file2.open(QIODevice::ReadOnly | QIODevice::Text)){
       while(!file2.atEnd()){
           QString data=file2.readLine();
           autolist.insert(data.split("|").at(0),data.split("|").at(1));
       }
       autolist.remove("#");
       file2.close();
   }

       drawlist();
}



bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{

    if (event->type()==6){
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);


        switch (keyEvent->key()) {
        case Qt::Key_Right:
        next();
        return true;
        break;


        case Qt::Key_Left:
        prev();
       return true;
        break;

        case Qt::Key_Space:
        play_pause();
        return true;
        break;

        case Qt::Key_Z:
        click1();
        return true;
        break;

        case Qt::Key_X:
        click2();
       return true;
        break;

        case Qt::Key_C:
        click3();
        return true;
        break;

        case Qt::Key_V:
        click4();
        return true;
        break;

        case Qt::Key_B:
        click5();
        return true;
        break;

        case Qt::Key_H:
        kbdhelp();
        return true;
        break;

        case Qt::Key_Q:
        if (keyEvent->modifiers()&&Qt::ControlModifier==keyEvent->modifiers()){
            qApp->exit();
            return true;}
        break;

        case Qt::Key_M:
        device->setMuted(!device->isMuted());
        return true;
        break;

        default:
            return QObject::eventFilter(obj, event); break;
        }
    } else {
        return QObject::eventFilter(obj, event);
    }
}


void MainWindow::keyPressEvent(QKeyEvent* event){
switch (event->key()) {
      case Qt::Key_F7:
    if (device->volume()+vol_change<=1)
          device->setVolume(device->volume()+vol_change);
    else
        device->setVolume(1);
          event->accept();
          break;
      case Qt::Key_F8:
          if (device->volume()-vol_change>=0)
          device->setVolume(device->volume()-vol_change);
          else
              device->setVolume(0);

          event->accept();
          break;
      default:
          QWidget::keyPressEvent(event);
          break;
}
}


void MainWindow::inform(){
QDialog dg;
QString text=tr("Filename : %1 <br />").arg(moo->currentSource().fileName());
 QMap<QString, QString> metaData = moo->metaData();
 QMapIterator<QString, QString> inf(metaData);
 while(inf.hasNext()){

     text+=inf.next().key()+" : "+inf.value()+"<br />";
 }
QScrollArea tu(&dg);
 QHBoxLayout *fg=new QHBoxLayout(&dg);
 fg->addWidget(&tu);

 QLabel t(QString(text),&tu);
tu.setWidget(&t);

dg.exec();
}



void MainWindow::sliderChanged (int val){
    QSlider* s = qobject_cast<QSlider*>(sender ());
    if (s)
    {
        int ind = sliders.indexOf(s);
        if (eqEffect)
            {
                double dval = (double)val;
                eqEffect->setParameterValue(eqEffect->parameters()[ind], dval);
            }
    }

}

void MainWindow::resetAll (){
       foreach (QSlider* s, sliders)
       {
       s->setValue(0);
       }
}

void MainWindow::toggleEqualizer(bool val)
{
    if (val){
       audioPath.insertEffect(eqEffect);
       set_setting ("eq_state","1");
   }
    else{
       audioPath.removeEffect (eqEffect);
       set_setting ("eq_state","0");
   }
}





void MainWindow::volumeChanged ( qreal newVolume ){
    set_setting("last_volume",QString("%1").arg(newVolume*100));
}

void MainWindow::load(){
    rotate=get_setting("rotate").toLong();
    QString fnt=get_setting("font");
    if (fnt.isEmpty())fnt="Nokia Sans,18,-1,5,50,0,0,0,0,0";
    QFont h(fnt);


    int size=get_setting("font_size").toLong();
    if (size==0)size=10;
    h.setPointSize(size);


    ui.listWidget->setFont(h);

    QString filter=get_setting("filter");
    if (filter.isEmpty())filter="*.mp3 *.flack *.ogg";
    namefilter=filter.split(" ");

scrobler=new last(get_setting("last_login"),get_setting("last_password"));

iload=get_setting("internet_load").toLong();
on_head_dis=get_setting("head_disconnect").toLong();
on_head_con=get_setting("head_connect").toLong();
on_start=get_setting("start_action").toLong();


QString bname=get_setting("FMTX-name");
if (bname.isEmpty())bname="N900";
ui.lineEdit->setText(bname);
bname=get_setting("FMTX-text");
if (bname.isEmpty())bname="%artist - %track";
ui.lineEdit_2->setText(bname);
double freq=get_setting("FMTX-freq").toDouble();
if (freq<88)freq=88.1;
ui.doubleSpinBox->setValue(freq);

int vol;
switch (get_setting("volume_behaviour").toLong()){
case 0:
    vol=100;
    break;
case 1:
 vol=get_setting("last_volume").toLong();
 break;
case 2:
 vol=0;
 break;
}
device->setVolume((qreal)vol/100);

size=get_setting("volume_change").toLong();
if (size==0)size=10;
vol_change=(qreal)(size)/100;

#ifdef Q_WS_MAEMO_5
 if (rotate==2){
 this-> setAttribute(Qt::WA_Maemo5AutoOrientation, true);
 }else if(rotate==1){
      setAttribute(Qt::WA_Maemo5PortraitOrientation, true);
 }else{
       setAttribute(Qt::WA_Maemo5LandscapeOrientation, true);
 }
#endif
}



void MainWindow::about(){
    QDialog *dwidget=new QDialog(0);
    QLabel *text=new QLabel(tr("<center><h3>TPlayer</h3></center><br />This program is distributed under terms of GNU GPL v3<br />" \
                            "Source code can be founded at <a href=\"http://googlecode.com/p/tplayer\">http://googlecode.com/p/tplayer</a><br /><br />" \
                            "Lead developer: <bold>Bonapart</bold><br />" \
                            "Web-developer : <bold>[vs]</bold>","you can insert translator info here"),dwidget);
    QPushButton *aqt=new QPushButton(tr("About Qt"),dwidget);
    QPushButton *kbd=new QPushButton(tr("Keyboard help"),dwidget);
    QVBoxLayout *mlay=new QVBoxLayout(dwidget);
    QHBoxLayout *dlay=new QHBoxLayout();
    connect(aqt,SIGNAL(clicked()),qApp,SLOT(aboutQt()));
    connect(kbd,SIGNAL(clicked()),this,SLOT(kbdhelp()));

    mlay->addWidget(text);
    mlay->addLayout(dlay);
    dlay->addWidget(aqt);
    dlay->addWidget(kbd);


dwidget->exec();
}
void MainWindow::kbdhelp(){
    QDialog *dg=new QDialog(0);
    QString text= QString(tr("left key - previous song<br />" \
                          "right key - next song<br />" \
                          "space key - play\\pause<br />" \
                          "m key - mute\\unmute<br />" \
                          "z - song tab<br />" \
                          "x - playlist tab<br />" \
                          "c - lyrics tab<br />" \
                          "v - biography tab<br />" \
                          "b - equalizer tab<br />" \
                          "h - this message<br />" \
                          "ctrl+q - quit"));


    QScrollArea tu(dg);
    QHBoxLayout *fg=new QHBoxLayout(dg);
    fg->addWidget(&tu);

    QLabel t(QString(text),&tu);
    tu.setWidget(&t);

dg->exec();
}

void MainWindow::fmtx_change(int state){
    try{
        set_setting("FMTX-name",ui.lineEdit->text());
        set_setting("FMTX-text",ui.lineEdit_2->text());
        set_setting("FMTX-freq",QString("%1").arg(ui.doubleSpinBox->value()));

    if (state==Qt::Checked){
        // enable

        QString txt=ui.lineEdit_2->text();
        if (inet_source!=1){
        txt.replace("%artist",list.value(ui.listWidget->currentRow()).at(2));
        txt.replace("%track",list.value(ui.listWidget->currentRow()).at(1));}
        else{

            QMap<QString, QString> metaData = moo->metaData();

            QString title = metaData.value("ORGANIZATION");
            if (title == "")
                title =moo->currentSource().url().toString();

        QString artist = metaData.value("LOCATION");

        txt.replace("%artist",title);
        txt.replace("%track",artist);
        }
        system(QString("fmtx_client -f %1 -s \"%2\" -t \"%3\" -p 1 >/dev/zero  2>/dev/zero").arg((int)(ui.doubleSpinBox->value()*1000)).arg(ui.lineEdit->text()).arg(txt).toAscii());
        system("sudo /sbin/fm-boost");

        ui.doubleSpinBox->setEnabled(false);
        ui.lineEdit->setEnabled(false);
        ui.lineEdit_2->setEnabled(false);

    }else{
        //disable

        system("fmtx_client -p 0 >/dev/zero  2>/dev/zero");

        ui.doubleSpinBox->setEnabled(true);
        ui.lineEdit->setEnabled(true);
        ui.lineEdit_2->setEnabled(true);
    }
}catch(int e){

}

}

MainWindow::~MainWindow()
{


}

void MainWindow::metaStateChanged(Phonon::State newState, Phonon::State /* oldState */)
{
    try{
 loading->setValue(loading->value()+1);

    if (newState == Phonon::ErrorState) {
        QMessageBox::warning(this, tr("Error opening files"),
            metaInformationResolver->errorString());

        queue.removeAt(queue.indexOf(metaInformationResolver->currentSource().fileName()));
        if (queue.count()> 0){

            metaInformationResolver->setCurrentSource(queue.first());

        }else{

                ld->close();
                    drawlist();
                }
        return;
    }

    if (newState != Phonon::StoppedState && newState != Phonon::PausedState)
        return;

    if (metaInformationResolver->currentSource().type() == Phonon::MediaSource::Invalid)
            return;

    QMap<QString, QString> metaData = metaInformationResolver->metaData();

    QString title = metaData.value("TITLE");
    if (title == "")
        title =metaInformationResolver->currentSource().fileName().split("/").last();

QString artist = metaData.value("ARTIST");
    if (artist=="")
        artist="Unknown";

QString album = metaData.value("ALBUM");
if (album=="")
    album="Unknown";
QString year = metaData.value("YEAR");
if (year=="")
    year="Unknown";
QString genre = metaData.value("GENRE");
if (genre=="")
    genre="Unknown";

QSqlQuery query(db);
QString sq="INSERT INTO tracks (path, title, artist, genre, album, year) "
           "VALUES ("
            "'"+metaInformationResolver->currentSource().fileName()+
            "','"+title+
            "','"+artist+
            "','"+genre+
            "','"+album+
            "','"+year+"')";

query.exec(sq);

queue.removeAt(queue.indexOf(metaInformationResolver->currentSource().fileName()));
if (queue.count() > 0){
    ld->setWindowTitle(queue.first());
        metaInformationResolver->setCurrentSource(queue.first());
    }
else{

    ld->close();
        drawlist();
    }

}catch(int e){
}
}



void MainWindow::clear(){
    db.exec("DELETE FROM tracks WHERE 1");
    drawlist();
}





void MainWindow::next(){
if (inet_source!=1){
    if ((float)moo->currentTime()/(float)moo->totalTime()>0.5)
        scrobler->addTrack(list.value(ui.listWidget->currentRow()),moo->totalTime());

if (ui.listWidget->count()==0)return;
    if (ui.listWidget->currentRow()<ui.listWidget->count()-1)
    ui.listWidget->setCurrentRow(ui.listWidget->currentRow()+1);
    else
        ui.listWidget->setCurrentRow(0);

     moo->setCurrentSource(list.value(ui.listWidget->currentRow()).at(0));
    moo->play();
}else{


    if ((float)moo->currentTime()/(float)moo->totalTime()>0.5)
        scrobler->addTrack(ilist.value(ui.listWidget_2->currentRow()),moo->totalTime());

if (ui.listWidget_2->count()==0)return;
    if (ui.listWidget_2->currentRow()<ui.listWidget_2->count()-1)
    ui.listWidget_2->setCurrentRow(ui.listWidget_2->currentRow()+1);
    else
        ui.listWidget_2->setCurrentRow(0);

     moo->setCurrentSource(ilist.value(ui.listWidget_2->currentRow()).at(0));
    moo->play();

}

}

void MainWindow::prev(){
    if (inet_source!=1){
    if (moo->currentTime()/moo->totalTime()>0.5)
        scrobler->addTrack(list.value(ui.listWidget->currentRow()),moo->totalTime());

if (ui.listWidget->count()==0)return;
    if (ui.listWidget->currentRow()>=0)
    ui.listWidget->setCurrentRow(ui.listWidget->currentRow()-1);
    else
        ui.listWidget->setCurrentRow(ui.listWidget->count()-1);

    moo->setCurrentSource(list.value(ui.listWidget->currentRow()).at(0));
    moo->play();
}else{


    if ((float)moo->currentTime()/(float)moo->totalTime()>0.5)
        scrobler->addTrack(ilist.value(ui.listWidget_2->currentRow()),moo->totalTime());

if (ui.listWidget_2->count()==0)return;
    if (ui.listWidget_2->currentRow()>0)
    ui.listWidget_2->setCurrentRow(ui.listWidget_2->currentRow()-1);
    else
        ui.listWidget_2->setCurrentRow(ui.listWidget_2->count()-1);

     moo->setCurrentSource(ilist.value(ui.listWidget_2->currentRow()).at(0));
    moo->play();

}

}

void MainWindow::play_pause(){

    if (moo->state()==Phonon::PlayingState )moo->pause();else moo->play();

}

void MainWindow::currentItemChanged ( QListWidgetItem * current ){
    set_setting("source_list","0");
    if (inet_source==0){
       emit track_change(list.value(ui.listWidget->row(current)).at(0));
    if (moo->currentTime()/moo->totalTime()>0.5)
        scrobler->addTrack(list.value(ui.listWidget->currentRow()),moo->totalTime());}else inet_source=0;
    moo->setCurrentSource(list.value(ui.listWidget->row(current)).at(0));
    moo->play();


}


void MainWindow::changePlay( Phonon::State newstate, Phonon::State oldstate ) {
    try{
        if (inet_source==0){
            set_setting("last_played",list.value(ui.listWidget->currentRow()).at(0) );


            emit this->track_change(moo->currentSource().fileName());

    ui.label->setText(list.value(ui.listWidget->currentRow()).at(2)+" - "+list.value(ui.listWidget->currentRow()).at(1));
    this->setWindowTitle(list.value(ui.listWidget->currentRow()).at(2)+" - "+list.value(ui.listWidget->currentRow()).at(1));
    if (newstate==Phonon::PlayingState&&oldstate!=Phonon::PausedState){

        track_title=list.value(ui.listWidget->currentRow()).at(1);
        track_artist=list.value(ui.listWidget->currentRow()).at(2);
        track_album=list.value(ui.listWidget->currentRow()).at(3);

scrobler->now(list.value(ui.listWidget->currentRow()),moo->totalTime());

#ifdef Q_WS_MAEMO_5
    if (!this->isActiveWindow()){
   QMaemo5InformationBox *box=new QMaemo5InformationBox();
   QLabel *lbl=new QLabel(tr("<center>Now playing : %1 - %2</center>").arg(list.value(ui.listWidget->currentRow()).at(2)).arg(list.value(ui.listWidget->currentRow()).at(1)),box);
  box->setWidget (lbl);
box->setTimeout(3000);
connect(box,SIGNAL(clicked()),this,SLOT(setFocus()));
box->exec();}
#endif
 }
    // fmtx
    if (ui.checkBox_2->isChecked()){
    QString txt=ui.lineEdit_2->text();
    txt.replace("%artist",list.value(ui.listWidget->currentRow()).at(2));
    txt.replace("%track",list.value(ui.listWidget->currentRow()).at(1));
    system(QString("fmtx_client -s \"%2\" -t \"%3\" >/dev/zero  2>/dev/zero").arg(ui.lineEdit->text()).arg(txt).toAscii());
    system("sudo /sbin/fm-boost");
}
    QString apath=QString(list.value(ui.listWidget->currentRow()).at(2)).toLower();
    apath.replace("/","");
    QString bpath=QString(apath+" - "+list.value(ui.listWidget->currentRow()).at(4)).toLower();
    bpath.replace("/","");

    QString cpath=base_path+".covers/";

    QString dpath=QString(list.value(ui.listWidget->currentRow()).at(1)).toLower();

    if (QFileInfo(cpath+bpath+".jpg").exists()){
        QPixmap *t=new QPixmap(cpath+bpath+".jpg");
                ui.image->setPixmap(t->scaled(400,300,Qt::KeepAspectRatio,Qt::FastTransformation));
    }else{
         if (QFileInfo(cpath+apath+".jpg").exists()){
            QPixmap *t=new QPixmap(cpath+apath+".jpg");
            ui.image->setPixmap(t->scaled(400,300,Qt::KeepAspectRatio,Qt::FastTransformation));

        }else{
            ui.image->setPixmap(QPixmap());
            if (iload>2){
                dart();
            }
        }


}
ui.textEdit->setText("");
ui.textEdit_2->setText("");

    QFile file(base_path+".bios/"+apath+".html");
    if (!file.exists()){
        if (iload>0){
         QUrl url("http://team16.ru/grab.php?bio="+apath);

         QNetworkAccessManager *manager = new QNetworkAccessManager(this);

          connect(manager, SIGNAL(finished(QNetworkReply*)),
                  this, SLOT(replyFinished(QNetworkReply*)));


          manager->get(QNetworkRequest(url));
      }
      }else{
          if (!file.open(QIODevice::ReadOnly|QFile::Text))  return ;

           QTextCodec *codec = QTextCodec::codecForName("UTF-8");

      ui.textEdit->setHtml( codec->toUnicode(file.readAll()));
      file.close();
      }

      QFile file2(base_path+".lyrics/"+apath+"-"+dpath+".html");
      if (!file2.exists()){
          if (iload>1){
           QUrl url("http://team16.ru/grab.php?band="+apath+"&lyrics="+dpath);

           QNetworkAccessManager *manager = new QNetworkAccessManager(this);

            connect(manager, SIGNAL(finished(QNetworkReply*)),
                    this, SLOT(replyFinished3(QNetworkReply*)));


            manager->get(QNetworkRequest(url));
        }
        }else{
            if (!file2.open(QIODevice::ReadOnly|QFile::Text))  return ;

             QTextCodec *codec = QTextCodec::codecForName("UTF-8");

        ui.textEdit_2->setHtml( codec->toUnicode(file2.readAll()));
        file2.close();
        }

        ui.pushButton_19->setEnabled(true);
    }else{

    set_setting("last_played_l",ilist.value(ui.listWidget_2->currentRow()).at(0) );

    if (moo->currentSource().url().toString().left(4)=="http"){

    if (ui.checkBox_2->isChecked())
    system("sudo /sbin/fm-boost");

        QMap<QString, QString> metaData = moo->metaData();

        QString title = metaData.value("ORGANIZATION");
        if (title == "")
            title =moo->currentSource().url().toString();

    QString artist = metaData.value("LOCATION");



        ui.label->setText(title+" - "+artist);
        this->setWindowTitle(title+" - "+artist);
        if (newstate==Phonon::PlayingState&&oldstate!=Phonon::PausedState){

  #ifdef Q_WS_MAEMO_5
       if (!this->isActiveWindow()){
       QMaemo5InformationBox *box=new QMaemo5InformationBox();
       QLabel *lbl=new QLabel(tr("Now playing : %1 - %2").arg(title).arg(artist),box);
      box->setWidget (lbl);
    box->setTimeout(3000);
    connect(box,SIGNAL(clicked()),this,SLOT(setFocus()));
    box->exec();}
    #endif


       QPixmap *t=new QPixmap(":/icons/inet.png");
       ui.image->setPixmap(t->scaled(400,300,Qt::KeepAspectRatio,Qt::FastTransformation));

       ui.pushButton_19->setEnabled(false);}

}else{
    //===========================================================================================================================================
    emit this->track_change(moo->currentSource().fileName());

    QMap<QString, QString> metaData = moo->metaData();

    track_title = metaData.value("TITLE");
    if (track_title == "")
        track_title =metaInformationResolver->currentSource().fileName().split("/").last();

    track_artist=metaData.value("ARTIST");
    track_album=metaData.value("ALBUM");

ui.label->setText(track_artist+" - "+track_title);
this->setWindowTitle(track_artist+" - "+track_title);
if (newstate==Phonon::PlayingState&&oldstate!=Phonon::PausedState){


//scrobler->now(list.value(ui.listWidget->currentRow()),moo->totalTime());

#ifdef Q_WS_MAEMO_5
if (!this->isActiveWindow()){
QMaemo5InformationBox *box=new QMaemo5InformationBox();
QLabel *lbl=new QLabel(tr("<center>Now playing : %1 - %2</center>").arg(track_artist).arg(track_title),box);
box->setWidget (lbl);
box->setTimeout(3000);
connect(box,SIGNAL(clicked()),this,SLOT(setFocus()));
box->exec();}
#endif
}
// fmtx
if (ui.checkBox_2->isChecked()){
QString txt=ui.lineEdit_2->text();
txt.replace("%artist",track_artist);
txt.replace("%track",track_title);
system(QString("fmtx_client -s \"%2\" -t \"%3\" >/dev/zero  2>/dev/zero").arg(ui.lineEdit->text()).arg(txt).toAscii());
system("sudo /sbin/fm-boost");
}

QString apath=QString(track_artist).toLower();
apath.replace("/","");
QString bpath=QString(apath+" - "+track_album).toLower();
bpath.replace("/","");

QString cpath=base_path+".covers/";

QString dpath=QString(track_title).toLower();

if (QFileInfo(cpath+bpath+".jpg").exists()){
QPixmap *t=new QPixmap(cpath+bpath+".jpg");
        ui.image->setPixmap(t->scaled(400,300,Qt::KeepAspectRatio,Qt::FastTransformation));
}else{
 if (QFileInfo(cpath+apath+".jpg").exists()){
    QPixmap *t=new QPixmap(cpath+apath+".jpg");
    ui.image->setPixmap(t->scaled(400,300,Qt::KeepAspectRatio,Qt::FastTransformation));

}else{
    ui.image->setPixmap(QPixmap());
    if (iload>2){
        dart();
    }
}


}
ui.textEdit->setText("");
ui.textEdit_2->setText("");

QFile file(base_path+".bios/"+apath+".html");
if (!file.exists()){
if (iload>0){
 QUrl url("http://team16.ru/grab.php?bio="+apath);

 QNetworkAccessManager *manager = new QNetworkAccessManager(this);

  connect(manager, SIGNAL(finished(QNetworkReply*)),
          this, SLOT(replyFinished(QNetworkReply*)));


  manager->get(QNetworkRequest(url));
}
}else{
  if (!file.open(QIODevice::ReadOnly|QFile::Text))  return ;

   QTextCodec *codec = QTextCodec::codecForName("UTF-8");

ui.textEdit->setHtml( codec->toUnicode(file.readAll()));
file.close();
}

QFile file2(base_path+".lyrics/"+apath+"-"+dpath+".html");
if (!file2.exists()){
  if (iload>1){
   QUrl url("http://team16.ru/grab.php?band="+apath+"&lyrics="+dpath);

   QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    connect(manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(replyFinished3(QNetworkReply*)));


    manager->get(QNetworkRequest(url));
}
}else{
    if (!file2.open(QIODevice::ReadOnly|QFile::Text))  return ;

     QTextCodec *codec = QTextCodec::codecForName("UTF-8");

ui.textEdit_2->setHtml( codec->toUnicode(file2.readAll()));
file2.close();
}

ui.pushButton_19->setEnabled(true);
    //===========================================================================================================================================
}



    }
    }catch(int e){
    }
}

void MainWindow::replyFinished(QNetworkReply*reply){

    QDir g;

    g.mkdir(base_path+".bios");
    QFile file(base_path+".bios/"+reply->url().toString().split("=").last()+".html");
        if (!file.open(QIODevice::WriteOnly))  return ;

  QString jk;
  QTextCodec *codec = QTextCodec::codecForName("UTF-8");

  jk=codec->toUnicode(reply->readAll());
  QTextStream out(&file);
        out <<jk;
        file.close();

    if (!file.open(QIODevice::ReadOnly|QFile::Text))  return ;
    QTextCodec *codec2 = QTextCodec::codecForName("UTF-8");
    ui.textEdit->setHtml( codec2->toUnicode(file.readAll()));
    file.close();

}

void MainWindow::replyFinished3(QNetworkReply*reply){

    QDir g;

    g.mkdir(base_path+".lyrics");
    QFile file(base_path+".lyrics/"+reply->url().queryItems().at(0).second+"-"+reply->url().queryItems().at(1).second+".html");
        if (!file.open(QIODevice::WriteOnly))  return ;

  QString jk;
  QTextCodec *codec = QTextCodec::codecForName("UTF-8");

  jk=codec->toUnicode(reply->readAll());
  QTextStream out(&file);
        out <<jk;
        file.close();

    if (!file.open(QIODevice::ReadOnly|QFile::Text))  return ;
    QTextCodec *codec2 = QTextCodec::codecForName("UTF-8");
    ui.textEdit_2->setHtml( codec2->toUnicode(file.readAll()));
    file.close();

}


void MainWindow::dart(){
    QString apath=QString(list.value(ui.listWidget->currentRow()).at(2)).toLower().replace("/","");
    QString bpath=QString(list.value(ui.listWidget->currentRow()).at(4)).toLower().replace("/","");
    QUrl url;
if (list.value(ui.listWidget->currentRow()).at(4)!="Unknown")
    url.setUrl("http://team16.ru/grab.php?image="+apath+"&album="+bpath);
             else
    url.setUrl("http://team16.ru/grab.php?image="+apath);


    QNetworkAccessManager *manager = new QNetworkAccessManager(this);

     connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished2(QNetworkReply*)));

     manager->get(QNetworkRequest(url));
}

void MainWindow::dart2(){
    QMessageBox f;
    f.setText(tr("This process will start in background\n Just wait when inet request speed slow down to zero\nI will create an progress bar in nearest future"));
    f.exec();
    for (int i=0;i<ui.listWidget->count();i++){
        ui.listWidget->setCurrentRow(i);
        dart();
    }

}



void MainWindow::replyFinished2(QNetworkReply*reply){
QByteArray data=reply->readAll();
    QDir g;
    QString fl;
    if (data==QString("404").toAscii()||data==QString("").toAscii()){
        if (reply->url().encodedQueryItems().count()!=1){
            QUrl url("http://team16.ru/grab.php?image="+reply->url().queryItems().at(0).second);
            QNetworkAccessManager *manager = new QNetworkAccessManager(this);

             connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished2(QNetworkReply*)));

             manager->get(QNetworkRequest(url));
        }
        return;
    }
    if (reply->url().encodedQueryItems().count()==1)
fl=reply->url().queryItems().at(0).second;
    else
     fl=reply->url().queryItems().at(0).second+" - "+reply->url().queryItems().at(1).second;

    g.mkdir(base_path+".covers");

    QFile file(base_path+".covers/"+fl+".jpg");
    if (!file.open(QIODevice::WriteOnly)){
        qDebug(QString::number(file.error()).toAscii());
        return ;}

 file.write(data);
    file.close();



    QMap<QString, QString> metaData = moo->metaData();

    QString track_artist=metaData.value("ARTIST");
    QString track_album=metaData.value("ALBUM");

    QString apath=QString(track_artist.toLower().replace("/",""));
    QString bpath=QString(apath+" - "+track_album.toLower().replace("/",""));


    QString cpath=base_path+".covers/";

    if (QFileInfo(cpath+bpath+".jpg").exists()){

        QPixmap *t=new QPixmap(cpath+bpath+".jpg");
        ui.image->setPixmap(t->scaled(400,300,Qt::KeepAspectRatio,Qt::FastTransformation));

    }else{
         if (QFileInfo(cpath+apath+".jpg").exists()){

            QPixmap *t=new QPixmap(cpath+apath+".jpg");
             ui.image->setPixmap(t->scaled(400,300,Qt::KeepAspectRatio,Qt::FastTransformation));

         }
}

}

void MainWindow::alistload(){
    QAction *t=(QAction *)sender();
currentQuery=autolist.value(t->text());

set_setting("query",currentQuery.trimmed());

drawlist();
}

void MainWindow::pl_sf_click(){
    lmast=new lmaster();
connect(lmast,SIGNAL(accepted()),this,SLOT(reload()));


    tmenu=new QMenu ();
    // autolist
    QMapIterator<QString,QString> item(autolist);
    while (item.hasNext()){
        item.next();
        tmenu->addAction(item.key(),this,SLOT(alistload()));
    }

    //
    tmenu->addSeparator();
    tmenu->addAction(tr("Master"),lmast,SLOT(exec()));

    tmenu->exec(QCursor::pos());
}

void MainWindow::pl_fn_click(){
QMenu fh;
QMenu add(tr("Add"));
QMenu mv(tr("Moving"));
fh.addMenu(&add);
fh.addMenu(&mv);
//add.addAction("Track",this,SLOT(pl_fn_add_track()));
add.addAction(tr("Directory"),this,SLOT(pl_fn_add_dir()));
fh.addAction(tr("Clear"),this,SLOT(clear()));
mv.addAction(tr("To begin"),ui.listWidget,SLOT(scrollToTop()));
mv.addAction(tr("To end"),ui.listWidget,SLOT(scrollToBottom()));
mv.addAction(tr("Find"),this,SLOT(find()));
 fh.exec(QCursor::pos());
}





void MainWindow::find(){
    bool ok;
         QString text = QInputDialog::getText(this, tr("Searching "),
                                              tr("Part from name:"), QLineEdit::Normal,
                                              "", &ok);
         if (ok && !text.isEmpty())
         {
             QMapIterator<int,QStringList> i(list);
             while(i.hasNext()){
                 if (i.next().value().join(" ").toLower().indexOf(text.toLower())!=-1){
                     ui.listWidget->setCurrentRow(i.key());
                     return;
                 }
             }
         }
}


void MainWindow::set_list(){
    QString lst=QFileDialog::getOpenFileName(this,tr("Open *.m3u"),"/home/user/MyDocs","*.m3u (*.m3u)",new QString("*.m3u (*.m3u)"));
    if (!lst.isEmpty())set_setting("list_path",lst);
    load_inet();

}

void MainWindow::i_fn_click(){
QMenu fh;

fh.addAction(tr("Load another *.m3u"),this,SLOT(set_list()));

fh.addAction(tr("To begin"),ui.listWidget_2,SLOT(scrollToTop()));
fh.addAction(tr("To end"),ui.listWidget_2,SLOT(scrollToBottom()));
fh.addAction(tr("Find"),this,SLOT(findi()));
fh.exec(QCursor::pos());
}

void MainWindow::findi(){
    bool ok;
         QString text = QInputDialog::getText(this, tr("Searching "),
                                              tr("Part from name:"), QLineEdit::Normal,
                                              "", &ok);
         if (ok && !text.isEmpty())
         {
             QMapIterator<int,QStringList> i(ilist);
             while(i.hasNext()){
                 if (i.next().value().join(" ").toLower().indexOf(text.toLower())!=-1){
                     ui.listWidget_2->setCurrentRow(i.key());
                     return;
                 }
             }
         }
}

void MainWindow::pl_fn_add_dir(){
    int l=0;
    ld=new QDialog();
    loading=new QProgressBar(ld);
    connect(ld,SIGNAL(rejected()),this,SLOT(ch()));
    QHBoxLayout *iu=new QHBoxLayout(ld);
    iu->addWidget(loading);


    QString d;
    QString f=QFileDialog::getExistingDirectory(this,"TPlayer","/home/user/MyDocs/.sounds",QFileDialog::ReadOnly);
   QApplication::processEvents();

    if (!f.isEmpty())
    {
        ld->setModal(true);
        ld->open();
        loading->setMaximum(100);
        loading->setValue(0);
         loading->show();
QApplication::processEvents();

QDir fg(f);
fg.setFilter(QDir::AllDirs|QDir::Files);
fg.setNameFilters(namefilter);


        QDirIterator it(fg, QDirIterator::Subdirectories|QDirIterator::FollowSymlinks);
        while (it.hasNext()) {
         d=it.next();
         QFileInfo hj(d);
         if (hj.isFile()){
l++;
ld->setWindowTitle(d);
                  getMeta(d);
                  QApplication::processEvents();
              }
    }
    }

    loading->setMaximum(l);
    loading->setValue(0);

    if (l>0){
    metaInformationResolver->setCurrentSource(queue.last());

    }else{

    ld->close();

}



}

void MainWindow::ch(){
    if (loading->value()<loading->maximum())ld->show();
}

void MainWindow::drawlist(){
    ui.listWidget->clear();
    list.clear();

    QSqlQuery query(currentQuery,db);
    int id=0;
    while ( query.next() ) {

        list.insert(id++,QStringList()<<
                    query.value(0).toString()<<
                    query.value(1).toString()<<
                    query.value(2).toString()<<
                    query.value(3).toString()<<
                    query.value(4).toString()<<
                    query.value(5).toString());
         ui.listWidget->addItem(query.value(2).toString()+"-"+query.value(1).toString());

    }

}



void MainWindow::getMeta(QString path){
queue.append(path);
}

void MainWindow::click1(){
    ui.frame_2->show();
    ui.frame_4->hide();
    ui.frame_6->hide();
    ui.frame_7->hide();
    ui.frame_8->hide();
    ui.frame_11->hide();
    ui.frame_12->hide();
    ui.frame_13->hide();

}

void MainWindow::click2(){
    ui.frame_2->hide();
    ui.frame_4->show();
    ui.frame_6->hide();
    ui.frame_7->hide();
    ui.frame_8->hide();
    ui.frame_11->hide();
    ui.frame_12->hide();
    ui.frame_13->hide();
}
void MainWindow::click3(){
    ui.frame_2->hide();
    ui.frame_4->hide();
    ui.frame_6->show();
    ui.frame_7->hide();
    ui.frame_8->hide();
    ui.frame_11->hide();
    ui.frame_12->hide();
    ui.frame_13->hide();
}
void MainWindow::click4(){
    ui.frame_2->hide();
    ui.frame_4->hide();
    ui.frame_6->hide();
    ui.frame_7->hide();
    ui.frame_8->show();
    ui.frame_11->hide();
    ui.frame_12->hide();
    ui.frame_13->hide();
}
void MainWindow::click5(){
    ui.frame_2->hide();
    ui.frame_4->hide();
    ui.frame_6->hide();
    ui.frame_7->show();
    ui.frame_8->hide();
    ui.frame_11->hide();
    ui.frame_12->hide();
    ui.frame_13->hide();
}

void MainWindow::click6(){
    ui.frame_2->hide();
    ui.frame_4->hide();
    ui.frame_6->hide();
    ui.frame_7->hide();
    ui.frame_8->hide();
    ui.frame_11->show();
    ui.frame_12->hide();
    ui.frame_13->hide();
}

void MainWindow::click7(){
    ui.frame_2->hide();
    ui.frame_4->hide();
    ui.frame_6->hide();
    ui.frame_7->hide();
    ui.frame_8->hide();
    ui.frame_11->hide();
    ui.frame_12->show();
    ui.frame_13->hide();
}

void MainWindow::click8(){
    ui.frame_2->hide();
    ui.frame_4->hide();
    ui.frame_6->hide();
    ui.frame_7->hide();
    ui.frame_8->hide();
    ui.frame_11->hide();
    ui.frame_12->hide();
    ui.frame_13->show();
}
